package com.example.rpc_core.servers;

import com.example.rpc_core.model.RpcRequestExample;
import com.example.rpc_core.model.RpcResponseExample;
import com.example.rpc_core.protocal.ProtocolMessage;
import com.example.rpc_core.protocal.ProtocolMessageDecoder;
import com.example.rpc_core.protocal.ProtocolMessageEnder;
import com.example.rpc_core.protocal.ProtocolMessageTypeEnum;
import com.example.rpc_core.register.impl.LocalRegister;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetSocket;
import java.io.IOException;
import java.lang.reflect.Method;


public class TcpServerHandle implements Handler<NetSocket> {
    @Override
    public void handle(NetSocket netSocket) {
        TcpBufferHandlerWrapper wrapper = new TcpBufferHandlerWrapper(TcpBuffer-> {
                //处理连接
                ProtocolMessage<RpcRequestExample>protocolMessage;
                try {
                    protocolMessage= (ProtocolMessage<RpcRequestExample>) ProtocolMessageDecoder.decode(TcpBuffer);
                } catch (IOException e) {
                    throw new RuntimeException("协议消息解码错误");
                }
                RpcRequestExample body = protocolMessage.getBody();

                //处理请求
                RpcResponseExample response = new RpcResponseExample();
                try {
                    Class<?> aClass = LocalRegister.get(body.getServiceName());
                    Method method = aClass.getMethod(body.getMethodName(), body.getParameterTypes());
                    Object invoke = method.invoke(aClass.newInstance(), body.getArgs());
                    //返回结果
                    response.setData(invoke);
                    response.setDataType(method.getReturnType());
                    response.setMessage("success");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                //发送响应,编码
                ProtocolMessage.Header header = protocolMessage.getHeader();
                header.setType((byte) ProtocolMessageTypeEnum.RESPONSE.getKey());
                ProtocolMessage<RpcResponseExample>responseProtocolMessage = new ProtocolMessage<>(header, response);


                try {
                    Buffer encode = ProtocolMessageEnder.encode(responseProtocolMessage);
                    netSocket.write(encode);
                } catch (IOException e) {
                    throw new RuntimeException("协议消息编码错误");
                }

            });
        netSocket.handler(wrapper);

    }
}
